package com.xiaohaoo.server.template.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaohaoo.server.template.entity.Product;
import com.xiaohaoo.server.template.entity.ResponseResult;
import com.xiaohaoo.server.template.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author xiaohao
 */
@RestController
@RequestMapping("product")
public class ProductController {
    @Autowired
    private ProductService productService;


    @GetMapping("{id}")
    public ResponseResult<Product> queryById(@PathVariable Integer id) {
        return ResponseResult.success(productService.getById(id));
    }


    @GetMapping(params = {"current"})
    public ResponseResult<Page<Product>> queryPage(@RequestParam Integer current,
                                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                                   Product product) {
        QueryWrapper<Product> query = Wrappers.query(product);
        return ResponseResult.success(productService.page(new Page<>(current, pageSize), query));
    }


    @GetMapping()
    public ResponseResult<List<Product>> queryList(Product product) {
        QueryWrapper<Product> query = Wrappers.query(product);
        return ResponseResult.success(productService.list(query));
    }


    @DeleteMapping("{id}")
    public ResponseResult<Void> delete(@PathVariable Integer id) {
        return productService.removeById(id) ? ResponseResult.success() : ResponseResult.error();
    }

    @PostMapping
    public ResponseResult<Void> save(@RequestBody Product product) {
        return productService.saveOrUpdate(product) ? ResponseResult.success() : ResponseResult.error();
    }
}
